package reuseplugin.views.benutzerListe;

import java.text.Collator;

import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;

import common.administration.Benutzer;

/**
 * @author Julius Ollesch
 * 
 */
public class BenutzerTableSorter extends ViewerSorter {
	private int propertyIndex;
	// private static final int ASCENDING = 0;
	private static final int DESCENDING = 1;

	private int direction = DESCENDING;

	public BenutzerTableSorter() {
		this.propertyIndex = 0;
		direction = DESCENDING;
	}

	@Override
	public int compare(Viewer viewer, Object o1, Object o2) {
		Benutzer b1 = (Benutzer) o1;
		Benutzer b2 = (Benutzer) o2;
		int rc = 0;
		switch (propertyIndex) {
		case 0:
			rc = Collator.getInstance().compare(b1.getVorname(),
					b2.getVorname());
			break;
		case 1:
			rc = Collator.getInstance().compare(b1.getNachname(),
					b2.getNachname());
			break;
		case 2:
			rc = Collator.getInstance().compare(b1.getBenutzername(),
					b2.getBenutzername());
			break;
		case 3:
			rc = Collator.getInstance().compare(b1.getEmailAdresse(),
					b2.getEmailAdresse());
			break;
		case 4:
			rc = Collator.getInstance().compare(
					b1.getDownloads().toArray().length,
					b2.getDownloads().toArray().length);
			break;
		case 5:
			rc = Collator.getInstance().compare(
					b1.getBenutzergruppe().getClass().getSimpleName(),
					b2.getBenutzergruppe().getClass().getSimpleName());
			break;
		default:
			rc = 0;
			break;
		}
		// If descending order, flip the direction
		if (direction == DESCENDING) {
			rc = -rc;
		}
		return rc;
	}

	public void setColumn(int column) {
		if (column == this.propertyIndex) {
			// Same column as last sort; toggle the direction
			direction = 1 - direction;
		} else {
			// New column; do an ascending sort
			this.propertyIndex = column;
			direction = DESCENDING;
		}
	}
}
